package com.weipai.demo.service.impl;

import com.weipai.demo.enums.RetCode;
import com.weipai.demo.mapper.UserMapper;
import com.weipai.demo.mapper.base.DUserMapper;
import com.weipai.demo.model.DUser;
import com.weipai.demo.service.UserService;
import com.weipai.demo.util.MD5Utils;
import com.weipai.demo.util.PasswordHelper;
import com.weipai.demo.util.PropUtils;
import com.weipai.demo.util.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * @author songmengqiang
 * @create 2018-08-29 19:00
 **/
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static int TIME_OUT = 3600 * 24 * 30;
    @Autowired
    private DUserMapper dUserMapper;
    @Autowired
    private UserMapper userMapper;
    /*@Autowired
    private SessionUserUtil sessionUserUtil;*/

    @Override
    public DUser getUserByLoginName(String userName) {
        DUser dUser= new DUser();
        dUser.setUserName(userName);
        DUser dUser1 = dUserMapper.selectOne(dUser);
        return dUser1;
    }

    @Override
    public DUser getUserByLoginUserId(String userId) {
        DUser dUser= new DUser();
        dUser.setUserId(userId);
        DUser dUser1 = dUserMapper.selectOne(dUser);
        return dUser1;
    }

    //登录
    @Override
    public Response login(String userName, String password, int type) {
        Response response = new Response();
        //查询此用户权限
        password = MD5Utils.encrypt(userName, password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            subject.getSession().setAttribute("token", token);

            int expire = (int) (System.currentTimeMillis() / 1000 + TIME_OUT);
            //int expire = 5;
            String authToken = PasswordHelper.generateToken(userName, expire, PropUtils.getString("system.secretKey"));

            response.put("Authentication-Token", authToken);
            response.put("Token", authToken);

            DUser dUser= new DUser();
            dUser.setUserName(userName);
            /*dUser.setType(type);*/
            DUser dUser1 = dUserMapper.selectOne(dUser);
            if(dUser1==null){
                response.setCode(RetCode.LOGIN_FAIL);
                response.setMsg(RetCode.LOGIN_FAIL.getMsg());
                return response;
            }else {
                //后台登录
                if(type==1){
                    //判断入参type和登录人信息是否相等
                    if(type!=dUser1.getType()){
                        response.setCode(RetCode.LOGIN_FAIL);
                        response.setMsg(RetCode.LOGIN_FAIL.getMsg());
                        return response;
                    }
                }


            }

            response.setCode(RetCode.SUCCESS);
            response.setMsg(RetCode.SUCCESS.getMsg());
            response.put("user",dUser1);
        } catch (IncorrectCredentialsException e) {
            logger.error("login error = {}", e.getMessage());
            //密码错误
            System.out.println(e.getMessage());
            response.setCode(RetCode.PWD_ERROR);
        } catch (AuthenticationException e) {
            response.setCode(RetCode.LOGIN_FAIL);
            logger.error("login error = {}", e.getMessage());
            System.out.println(e.getMessage());
        } catch (Exception e) {
            logger.error("login error = {}", e.getMessage());
            response.setCode(RetCode.LOGIN_FAIL);
        }
        logger.info("是否登录：" + subject.isAuthenticated());
        return response;

    }

    @Override
    public Response saveUser(String userName, String password, String email) {
        Response response = new Response();
        DUser dUser= new DUser();
        if(StringUtils.isEmpty(userName)){
            response.setCode(RetCode.COLD_ALL);
            return response;
        }

        if(StringUtils.isEmpty(password)){
            response.setCode(RetCode.COLD_ALL);
            return response;
        }
        if(StringUtils.isEmpty(email)){
            response.setCode(RetCode.COLD_ALL);
            return response;
        }

        try {
            int count=userMapper.getUserByUserName(userName);
            if(count>0){
                logger.info("添加用户失败:{}", "登录名不能重复");
                response.setCode(RetCode.D_RESULT_FAIL_NAMEVAR);
                response.setMsg("登录名不能重复");
                return response;
            }

            int countEmail=userMapper.getUserByEmail(email);
            if(count>0){
                logger.info("添加用户失败:{}", "邮箱不能重复");
                response.setCode(RetCode.D_RESULT_FAIL_NAMEVAR);
                response.setMsg("邮箱不能重复");
                return response;
            }
            dUser.setUserName(userName);
            password = MD5Utils.encrypt(userName, password);
            dUser.setUserPassword(password);
            dUser.setCreateName("系统注册");
            dUser.setUserEmail(email);
            dUser.setUserId(UUID.randomUUID().toString());
            logger.info("注册用户："+dUser.toString());
            dUserMapper.insertSelective(dUser);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("",e.getMessage());
            response.setCode(RetCode.REQUEST_ERROR);
            response.setMsg(RetCode.REQUEST_ERROR.getMsg());
            return response;
        }
        response.setCode(RetCode.SUCCESS);
        response.setMsg(RetCode.SUCCESS.getMsg());
        return response;
    }

    @Override
    public Response loginOut() {
        Response response = new Response();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
       /* User user = (User) subject.getSession().getAttribute(User.KEY);*/
       /* logger.info("user {}", user);*/
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    /**
     *
     * 修改密码
     * @author gusl
     * @date 2019/5/31 17:41
     * @param  [userId, oldPassword, newPassword, twoPassword]
     * @return com.weipai.springboot.model.api.Response
     */

    @Override
    public Response resetUserPassword(String userId, String oldPassword, String newPassword, String twoPassword) {
        Response response = new Response();
        //判断两次密码是否一样
        try {
            if (!newPassword.equals(twoPassword)) {
                response.setCode(RetCode.PASSWORD_NOT_SAME);
            } else {
                if (null == userId) {
                   /* userId = sessionUserUtil.getUserAttr().getUserId();*/
                }
                DUser dUser = this.getUserByLoginUserId(userId);
                if(!Objects.isNull(dUser)){
                    logger.info("修改密码DUser："+dUser.toString());
                    DUser dUserTo=new DUser();
                    String password = MD5Utils.encrypt(dUser.getUserName(), newPassword);
                    dUser.setUserPassword(password);
                    if (1 == dUserMapper.updateByPrimaryKeySelective(dUser)) {
                        response.setCode(RetCode.SUCCESS);
                        response.setMsg(RetCode.SUCCESS.getMsg());
                    } else {
                        response.setCode(RetCode.REQUEST_ERROR);
                        response.setMsg(RetCode.REQUEST_ERROR.getMsg());
                    }
                }else {
                    logger.info("无此用户");
                    response.setCode(RetCode.REQUEST_ERROR);
                    response.setMsg(RetCode.REQUEST_ERROR.getMsg());
                    return response;
                }



            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("resetUserPassword异常："+e.getMessage());
            response.setCode(RetCode.REQUEST_ERROR);
            response.setMsg(RetCode.REQUEST_ERROR.getMsg());
        }
        return response;
    }


}
